package com.zdp.contentcenter.feignclient.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sesshomaru
 * @date 2020/9/27 21:03
 *
 * 基于加token的feign拦截器
 */
public class TokenRelayRequestInteceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 1.获取到token
        // spring提供的静态方法获取request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("x-token");
        if (StringUtils.isNotBlank(token)) {
            // 2.将token传递
            requestTemplate.header("x-token",token);
        }
    }
}
